from common.selenium import *
from selenium.webdriver.common.by import By
from settings import ENV

# 新增 Page 引用
from .home_page import HomePage
from .login_page import LoginPage


class Event:
    def event_login(self, driver, username, password):
        driver.get(ENV.url)
        # 通过 Page Object 完成登录
        home = HomePage(driver)
        home.goto_login()
        LoginPage(driver).login(username, password)

    def event_register(self, driver, username, password, email, confirm_pwd=None):
        # 直接进入注册页面，避免首页点击失败或元素改变
        driver.get(ENV.register_url)

        # 如果未显式传入确认密码，默认与 password 相同
        if confirm_pwd is None:
            confirm_pwd = password

        # -------- 输入注册信息（兼容 id 与 placeholder 变动） --------
        object_send_keys(
            driver,
            (
                By.XPATH,
                "//input[@id='user_name' or @placeholder='请输入用户名' or @name='username']",
            ),
            username,
        )
        object_send_keys(
            driver,
            (
                By.XPATH,
                "//input[@id='pwd' or @placeholder='请输入密码' or @name='password']",
            ),
            password,
        )
        object_send_keys(
            driver,
            (
                By.XPATH,
                "//input[@id='cpwd' or @placeholder='请再次输入密码' or @name='confirm_pwd']",
            ),
            confirm_pwd,
        )
        object_send_keys(
            driver,
            (
                By.XPATH,
                "//input[@id='email' or @placeholder='请输入邮箱' or @name='email']",
            ),
            email,
        )

        # 点击注册按钮（兼容不同 value 文本）
        object_left_click(
            driver,
            (
                By.XPATH,
                "//input[( @value='注 册' or normalize-space(@value)='注册' )]",
            ),
            retries=2,
        )
